import { HttpException, HttpStatus, Injectable, } from '@nestjs/common';
import { CreateSqlTestDto } from './dto/create-sql-test.dto';
import { UpdateSqlTestDto } from './dto/update-sql-test.dto';
import { User } from '../../entity/user.entity'
import { IdCard } from 'src/entity/idCard.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
@Injectable()
export class SqlTestService {
  constructor(@InjectRepository(User) private readonly userRepository: Repository<User>, @InjectRepository(IdCard) private readonly idCardRepository: Repository<IdCard>) { }

  /**
   * 实体没有加级联，需要手动保存idCard
   * @param createSqlTestDto 
   * @returns 
   */
  async create(createSqlTestDto: CreateSqlTestDto) {
    try {

      const idCard = new IdCard();
      idCard.cardId = createSqlTestDto.cardId;
      idCard.cardName = '身份证';
      const user = new User();
      // user.idCard = idCard;
      idCard.user = user; // 外键关联
      console.log('card', idCard);
      user.name = createSqlTestDto.name;
      await this.userRepository.save(user); // 数据库操作是异步的
      //b没有级联需要手动保存
      await this.idCardRepository.save(idCard);
      return '新增用户成功'
    } catch (error) {
      throw new HttpException('新增用户失败', HttpStatus.BAD_REQUEST)
    }
  }

  findAll() {
    return this.userRepository.find({
      // 关联查询
      relations: ['idCard'],
      order: {
        id: "DESC"
      },
      // skip: (query.page - 1)* query.pageSize,
      // take:query.pageSize,


    })
  }

  findOne(id: number) {
    return this.userRepository.findOne({
      where: { id: id },
    })
  }

  /**
   * save方法更新
   * @param updateSqlTestDto 
   * @returns 
   */
  async update(updateSqlTestDto: UpdateSqlTestDto) {
    try {


      if (!updateSqlTestDto.id) {
        throw new HttpException('id不能为空', HttpStatus.BAD_REQUEST)
      }
      const user = await this.userRepository.findOne({
        relations: ['idCard'],
        where: { id: updateSqlTestDto.id }
      })

      if (!user) {
        throw new HttpException('用户不存在', HttpStatus.NOT_FOUND);
      }

      user.name = updateSqlTestDto.name;
      await this.userRepository.save(user)


      // 更新card
      if (user.idCard) {
        user.idCard.cardId = updateSqlTestDto.cardId;
        await this.idCardRepository.save(user.idCard)
      }

      return '修改成功'
    } catch (error) {
      throw new HttpException('更新失败', HttpStatus.BAD_REQUEST);

    }


  }

  /**
   * update方法更新
   * @param updateSqlTestDto 
   * @returns 
   */
  async update2(updateSqlTestDto: UpdateSqlTestDto) {
    console.log('updateSqlTestDto', updateSqlTestDto);
    if (!updateSqlTestDto.id) {
      throw new HttpException('id不能为空', HttpStatus.BAD_REQUEST)
    }
    const user = await this.userRepository.findOne({
      relations: ['idCard'],
      where: { id: updateSqlTestDto.id }
    })
    const user1 = new User();
    user1.name = updateSqlTestDto.name;

    console.log('user', user);
    console.log('user1', user1);
    await this.userRepository.update(updateSqlTestDto.id, user1)
    // 更新card
    if (user.idCard) {
      // const card = new IdCard()
      // update更新不需要创建一个新的实体
      const card = {
        cardId: updateSqlTestDto.cardId,
      }
      // card.user = user1; 不能加，否则会报错
      await this.idCardRepository.update(user.idCard.id, card)
    }


    return '修改成功'


  }


  async remove(id: number) {
    try {
      // 异步需要加await
      const user = await this.userRepository.findOne({
        relations: ['idCard'],
        where: { id: id }
      })

      if (!user) {
        throw new HttpException('用户不存在', HttpStatus.NOT_FOUND);
      }
      if (user.idCard) {
        await this.idCardRepository.remove(user.idCard)

      }
      await this.userRepository.remove(user)
      return '删除成功' + id
    } catch (error) {
      throw new HttpException('更新失败', HttpStatus.BAD_REQUEST);

    }
  }
}
